package com.srwl.mytx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.ReasonsAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.OrderService;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.Utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RefundActivity extends BaseActivity {
    private static final String TAG = "OrderDetailActivity";

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_topic_title)
    TextView tv_topicTitle;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_order_id)
    TextView tv_orderId;
    @BindView(R.id.et_refund)
    EditText et_refund;
    @BindView(R.id.et_reason)
    TextView et_reason;
    @BindView(R.id.btn_pay_order)
    Button btn_commit;
    @BindView(R.id.btn_cancel)
    Button btn_cancel;
    @BindView(R.id.tv_order_status)
    TextView tv_orderStatus;
    @BindView(R.id.rv_reasons)
    RecyclerView rv_reasons;
    @BindView(R.id.tv_send_status)
    TextView tv_sendStatus;
    @BindView(R.id.spinner)
    AppCompatSpinner spinner;
    @BindView(R.id.place_holder)
    View placeHolder;
    @BindView(R.id.ll_spinner)
    LinearLayout ll_spinner;

    private Orders order;
    private Topic topic;
    private ReasonsAdapter reasonsAdapter;
    private Integer buyerSelectStatus;
    private boolean isSeller;
    private boolean isSent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund);
        ButterKnife.bind(this);
        toolbar.setNavigationOnClickListener(v -> finish());
        order = getIntent().getParcelableExtra(Constant.EXTRA_INFO_ORDER);
        topic = order.getTopic();
        if (order == null) {
            throw new RuntimeException("order can't empty");
        }
        setViewAndEvent();
    }

    private void setViewAndEvent() {
        if (order.getReasons().size() == 0) {
            placeHolder.setVisibility(View.GONE);
        }
        rv_reasons.setLayoutManager(new LinearLayoutManager(this));
        reasonsAdapter = new ReasonsAdapter(this, order.getReasons());
        rv_reasons.setAdapter(reasonsAdapter);
        rv_reasons.setNestedScrollingEnabled(false);
        tv_topicTitle.setText(order.getTitle());
        et_reason.setText("");
        tv_amount.setText(Utils.moneyFormat(order.getAmount()));
        isSeller = UserProfileManager.getInstance().getLoginUserInfo().getuId().equals(order.getSellerId());
        //发货标记
        isSent = Constant.ORDER_SEND_STATUS_SENT == order.getSendStatus();
        hideAllButton();
        switch (order.getStatus()) {

            case Constant.ORDER_STATUS_CONFLICT:
                tv_orderStatus.setText("问题处理中...");
                if (isSeller) {
                    showAgreeRefund();
                } else {
                    showCancelRefund();
                }
                break;

            case Constant.ORDER_STATUS_PAID:
                tv_orderStatus.setText("已经支付");
                showCommitRefund();
                break;
            case Constant.ORDER_STATUS_REFUNDING:
                onRefunding();
                break;
            case Constant.ORDER_STATUS_REFUND_COMPLETED:
                tv_orderStatus.setText("退款完成");
                break;
            case Constant.ORDER_STATUS_REFUSE_REFUND:
                tv_orderStatus.setText("卖家拒绝退款");

                if (isSeller) {
                    showAgreeRefund();
                } else {
                    showEditRefund();
                    showCancelRefund();
                }
                break;
            case Constant.ORDER_STATUS_AGREE_REFUND:
                tv_orderStatus.setText("卖家同意退款");
                if (!isSeller) {
                    showRefundGoods();
                    showCancelRefund();
                }
                break;
        }


        if (isSent) {
            tv_sendStatus.setText("已发货");

        } else if (Constant.ORDER_SEND_STATUS_WAIT_SEND == order.getSendStatus()) {
            tv_sendStatus.setText("未发货");

        }

        tv_orderId.setText(order.getId());
        if (order.getRefund() != null) {
            et_refund.setText(Utils.moneyFormat(order.getRefund()));
        }
        if (isSeller) {//卖家
            ll_spinner.setVisibility(View.GONE);
            et_refund.setFocusable(false);
            et_reason.setHint("输入拒绝原因");
            btn_commit.setEnabled(true);
        } else {
            checkOrderSendStatus();
            btn_commit.setOnClickListener(v -> refund());
            et_reason.setHint("输入退款原因");
        }
    }

    private void onRefunding() {
        switch (order.getRefundStatus()) {
            case Constant.ORDER_REFUND_STATUS_NOT_RECEIVED_REFUND_ALL:
                if (isSent) {
                    tv_orderStatus.setText("买家未收货,发起全额退款，等待卖家确认");
                } else {
                    tv_orderStatus.setText("买家发起全额退款，等待卖家确认");
                }
                if (isSeller) {
                    showRefuseRefund();
                    showAgreeRefund();
                } else {
//                    if (isSent) {//在未收货的退款中，如果已经发货了，显示修改退款的按键，因为在未发货的情况，只能申请退全款，一旦发起退款，没有修改的必要
//                    }
                    showEditRefund();
                    showCancelRefund();
                }
                break;
            case Constant.ORDER_REFUND_STATUS_RECEIVED_REFUND_ALL:
                tv_orderStatus.setText("买家已收货，发起全额退款并退货，等待卖家确认");
                if (isSeller) {
                    showRefuseRefund();
                    showAgreeRefund();
                } else {
                    showEditRefund();
                    showCancelRefund();
                }
                break;
            case Constant.ORDER_REFUND_STATUS_RECEIVED_REFUND_PART:
                tv_orderStatus.setText("买家已收货，发起部分退款，不退货，等待卖家确认");
                if (isSeller) {
                    showRefuseRefund();
                    showAgreeRefund();
                } else {
                    showEditRefund();
                    showCancelRefund();
                }
                break;
        }
    }

    private void checkOrderSendStatus() {
        if (order.getSendStatus() == Constant.ORDER_SEND_STATUS_WAIT_SEND) {//如果没有发货，设置为退全款，退款金额编辑框不能编辑
            refundAll();
            btn_commit.setEnabled(true);
            ll_spinner.setVisibility(View.GONE);

        } else {//已经发货，显示选择框，让买家选择是退货退款，还是仅仅退款
            showSpinner();
            initInputListener();
        }
    }

    private void hideAllButton() {
        btn_cancel.setVisibility(View.GONE);
        btn_commit.setVisibility(View.GONE);
    }

    private void showAgreeRefund() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("同意退款");
        btn_commit.setOnClickListener(v -> agreeRefund());
    }

    private void showRefuseRefund() {
        btn_cancel.setVisibility(View.VISIBLE);
        btn_cancel.setText("拒绝退款");
        btn_cancel.setOnClickListener(v -> refuseRefund());
    }

    //第一次发起退款
    private void showCommitRefund() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("发起退款");
        btn_commit.setOnClickListener(v -> refund());
    }

    //修改退款
    private void showEditRefund() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("修改退款");
        btn_commit.setOnClickListener(v -> refund());
    }    //修改退款

    private void showRefundGoods() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("退货");
        btn_commit.setOnClickListener(v -> refundGoods());
    }


    private void showCancelRefund() {
        btn_cancel.setText("取消退款");
        btn_cancel.setVisibility(View.VISIBLE);
        btn_cancel.setOnClickListener(v -> cancelRefund());
    }

    private void showSpinner() {
        ll_spinner.setVisibility(View.VISIBLE);
        ArrayList<String> data_list = new ArrayList<String>();
        data_list.add("未收货全额退款");
        data_list.add("全额退款并退货");
        data_list.add("部分退款不退货");
        ArrayAdapter<String> arr_adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, data_list);
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arr_adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    buyerSelectStatus = Constant.ORDER_REFUND_STATUS_NOT_RECEIVED_REFUND_ALL;
                    refundAll();
                } else if (position == 1) {
                    buyerSelectStatus = Constant.ORDER_REFUND_STATUS_RECEIVED_REFUND_ALL;
                    refundAll();
                } else {
                    buyerSelectStatus = Constant.ORDER_REFUND_STATUS_RECEIVED_REFUND_PART;
                    refundPart();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 退全款
     * 退款金额编辑框不能编辑
     * 设置为订单金额
     */
    private void refundAll() {
        et_refund.setFocusable(false);
        et_refund.setText(Utils.moneyFormat(order.getAmount()));
    }

    private void refundPart() {
        et_refund.setFocusable(true);
        et_refund.setText("");
    }

    //退货，保存退货物理信息等
    private void refundGoods() {

    }


    //取消退款
    private void cancelRefund() {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .cancelRefund(order.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        showToast(btn_commit, "取消退款完成");
                        order.setStatus(Constant.ORDER_STATUS_PAID);//取消退款后，重新设置状态为已付款
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    private void initInputListener() {
        MoneyInputCheck moneyInputCheck = new MoneyInputCheck(this, 0.01, order.getAmount(), new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                btn_commit.setEnabled(false);
                et_refund.setError(message);
            }

            @Override
            public void waitInput() {
                btn_commit.setEnabled(false);
            }

            @Override
            public void inputRight() {
                btn_commit.setEnabled(true);
            }
        });

        et_refund.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                moneyInputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                moneyInputCheck.onTextChanged(s);
            }
        });
    }


    private void refund() {
        String refund = et_refund.getText().toString();
        Orders updateOrder = new Orders();
        if (order.getSendStatus() == Constant.ORDER_SEND_STATUS_WAIT_SEND) {
            updateOrder.setRefundStatus(Constant.ORDER_REFUND_STATUS_NOT_RECEIVED_REFUND_ALL);//设置为 未收到货退全款
        } else {//根据买家选择是退款退货还是仅退款
            updateOrder.setRefundStatus(buyerSelectStatus);
        }
        updateOrder.setId(order.getId());
        updateOrder.setRefund(BigDecimal.valueOf(Double.valueOf(refund)).setScale(2, RoundingMode.HALF_DOWN).doubleValue());
        String reason = et_reason.getText().toString();
        if (!TextUtils.isEmpty(reason)) {
            updateOrder.addReason("买家：" + reason);
        }
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .refund(updateOrder)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.ORDER_STATUS_ERROR:

                                    showToast("当前订单状态已过时，正在同步最新订单状态");
                                    syncOrderData(order.getId());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }

                            return;
                        }
//                        JSONObject data = (JSONObject) result.getData();
//                        Log.d(TAG, "onResponse: 发起退款完成" + data.toJSONString());
                        int refundCount = order.getRefundCount();
                        order.setRefundCount(refundCount + 1);
                        if (order.getStatus() == Constant.ORDER_STATUS_REFUNDING) {
                            showToast("修改退款完成");
                        } else {
                            showToast("发起退款完成");
                        }

                        order.setStatus(Constant.ORDER_STATUS_REFUNDING);
                        order.setRefundStatus(updateOrder.getRefundStatus());
                        order.setRefund(updateOrder.getRefund());
                        if (!TextUtils.isEmpty(reason)) {
                            order.addReason("买家：" + reason);
                        }
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    private void syncOrderData(String orderId) {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .syncOrderData(orderId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 同步订单信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        order = body.toJavaObject(Orders.class);
                        order.setTopic(topic);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    /**
     * 同意退款
     */
    private void agreeRefund() {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .agreeRefund(order)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        showToast(btn_commit, "同意退款完成");
                        if (order.getSendStatus() == Constant.ORDER_SEND_STATUS_WAIT_SEND) {//没有发货的订单，退款后交易终止
                            order.setStatus(Constant.ORDER_STATUS_REFUND_COMPLETED);
                        } else {//已经发货的订单，设置订单状态为 同意退款，需要 买家退回商品
                            order.setStatus(Constant.ORDER_STATUS_AGREE_REFUND);
                        }
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });

    }

    /**
     * 拒绝退款
     */
    private void refuseRefund() {
        Orders updateOrder = new Orders();
        updateOrder.setId(order.getId());
        String reason = et_reason.getText().toString();
        if (!TextUtils.isEmpty(reason)) {
            order.addReason("卖家：" + reason);
            updateOrder.setReasons(order.getReasons());
        }


        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .refuseRefund(order)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        showToast(btn_commit, "拒绝退款完成");
                        order.setStatus(Constant.ORDER_STATUS_REFUSE_REFUND);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }


}
